{% extends "layout.html" %}

{% block title %}Création d'une ligne mobile{% endblock %}

{% block content %}
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="js/vendor/jquery.validate.js"></script>
<script src="js/vendor/datepicker/js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="js/vendor/datepicker/css/datepicker.css">
<style>
  .custom-combobox {
    position: relative;
    display: inline-block;
  }
  .custom-combobox-toggle {
    position: absolute;
    top: 0;
    bottom: 0;
    margin-left: -1px;
    padding: 0;
    /* support: IE7 */
    *height: 1.7em;
    *top: 0.1em;
  }
  .custom-combobox-input {
    margin: 0;
    padding: 0.3em;
  }
  </style>
  <script>
  (function( $ ) {
    $.widget( "custom.combobox", {
      _create: function() {
        this.wrapper = $( "<span>" )
          .addClass( "custom-combobox" )
          .insertAfter( this.element );
 
        this.element.hide();
        this._createAutocomplete();
        this._createShowAllButton();
      },
 
      _createAutocomplete: function() {
        var selected = this.element.children( ":selected" ),
          value = selected.val() ? selected.text() : "";
 
        this.input = $( "<input>" )
          .appendTo( this.wrapper )
          .val( value )
          .attr( "title", "" )
          .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
          .autocomplete({
            delay: 0,
            minLength: 0,
            source: $.proxy( this, "_source" )
          })
          .tooltip({
            tooltipClass: "ui-state-highlight"
          });
 
        this._on( this.input, {
          autocompleteselect: function( event, ui ) {
            ui.item.option.selected = true;
            this._trigger( "select", event, {
              item: ui.item.option
            });
          },
 
          autocompletechange: "_removeIfInvalid"
        });
      },
 
      _createShowAllButton: function() {
        var input = this.input,
          wasOpen = false;
 
        $( "<a>" )
          .attr( "tabIndex", -1 )
          .attr( "title", "Voir toutes les SIM" )
          .tooltip()
          .appendTo( this.wrapper )
          .button({
            icons: {
              primary: "ui-icon-triangle-1-s"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass( "custom-combobox-toggle ui-corner-right" )
          .mousedown(function() {
            wasOpen = input.autocomplete( "widget" ).is( ":visible" );
          })
          .click(function() {
            input.focus();
 
            // Close if already visible
            if ( wasOpen ) {
              return;
            }
 
            // Pass empty string as value to search for, displaying all results
            input.autocomplete( "search", "" );
          });
      },
 
      _source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
        response( this.element.children( "option" ).map(function() {
          var text = $( this ).text();
          if ( this.value && ( !request.term || matcher.test(text) ) )
            return {
              label: text,
              value: text,
              option: this
            };
        }) );
      },
 
      _removeIfInvalid: function( event, ui ) {
 
        // Selected an item, nothing to do
        if ( ui.item ) {
          return;
        }
 
        // Search for a match (case-insensitive)
        var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
        this.element.children( "option" ).each(function() {
          if ( $( this ).text().toLowerCase() === valueLowerCase ) {
            this.selected = valid = true;
            return false;
          }
        });
 
        // Found a match, nothing to do
        if ( valid ) {
          return;
        }
 
        // Remove invalid value
        this.input
          .val( "" )
          .attr( "title", value + " : pas de correspondances" )
          .tooltip( "open" );
        this.element.val( "" );
        this._delay(function() {
          this.input.tooltip( "close" ).attr( "title", "" );
        }, 2500 );
        this.input.data( "ui-autocomplete" ).term = "";
      },
 
      _destroy: function() {
        this.wrapper.remove();
        this.element.show();
      }
    });
  })( jQuery );
 
  $(function() {
    $( "#combobox" ).combobox();
    $( "#toggle" ).click(function() {
      $( "#combobox" ).toggle();
    });
  });
  </script>
<script>
//if (jQuery) { alert("jQuery loaded"); }
$.validator.setDefaults({
	submitHandler: function() { 
	//alert("envoyé!");
	submit();
	}
});
jQuery.validator.addMethod("numero_tel", function(value, element) {
        // test du numéro
        return /^33\d\d\d\d\d\d\d\d\d$/i.test(value);
    }, 'Veuillez saisir le numéro de téléphone dans le format suivant : <i>33123456789</i>');

jQuery.validator.addMethod("format_date", function(value, element) {
        // test du numéro
	return /^\d\d?\/\d\d?\/\d\d\d\d$/i.test(value);
    }, 'Format jj/mm/aaaa');	

jQuery.validator.addMethod("alphanumerique", function(value, element) {
	return this.optional(element) || /^[a-z0-9\-\_\s]+$/i.test(value);
}, "Pas de caractères spéciaux.");	

$().ready(function() {
	
	// validation du formulaire par keyup et submit
	$("#form").validate({
		rules: {
			utilisateur: {
				required: true,
				minlength: 2,
				alphanumerique: true
			},
			numero_rio: {
				required: true,
				minlength: 12,
				maxlength: 12
			},
			msisdn: {
				required: true,
				minlength: 11,
				maxlength: 11,
				alphanumerique: true,
				numero_tel: true
			},
			date_souhaite: {
				required: true,
				minlength: 10,
				maxlength: 10,
				format_date: true
			},
			engagement: {
				required: true
			},
			abonnement_mobile: {
				required: true
			},
			terminal_mobile: {
				required: true
			}
		},
		messages: {
			utilisateur: {
				required: "Champ obligatoire",
				minlength: "Ce champ doit contenir au moins 2 caractères",
				alphanumerique: "Pas de caractères spéciaux"
			},
			numero_rio: {
				required: "Champ obligatoire",
				minlength: "Ce champ doit contenir 12 caractères"
			},
			msisdn: {
				required: "Champ obligatoire",
				minlength: "Ce champ doit contenir 11 caractères"
			},
			date_souhaite: {
				required: "Champ obligatoire",
				minlength: "Ce champ doit contenir 10 caractères"
			},
			engagement: {
				required: "Champ obligatoire",
			}

		}
	});
});

$(function(){
$('#date_souhaite').datepicker({
				format: 'dd/mm/yyyy',
				weekStart: 1,
				startDate: '+3d',
    			endDate: '+59d',
				daysOfWeekDisabled: '0,7',
				language: 'fr-FR'
				
			});
});
$(function() {
	$('#offre').bind('change', function(ev) {
		
		var value = $(this).val();
		
		$.ajax({
		type: "GET",
		url: "ajout-ligne-mobile-options",
		data: "test=ok&id_forfait="+value+"&id={{ligneCommande.id}}&commande={{commande.id}}",
		error:function(msg){
		 alert( "Error !: " + msg );
		},
		success:function(data){
			//affiche le contenu du fichier dans le conteneur dédié
			$('#contenu_options_ajax').html(data);}
	 	});
		
		//Affichage du prix
		var engagement = $('input[name="engagement"]:checked').val();
		var equipement = $('select[name="terminal_mobile"]').val();
		$.ajax({
		type: "GET",
		url: "affiche-prix",
		data: "id_forfait="+value+"&engagement="+engagement+"&equipement="+equipement+"&type=mobile",
		error:function(msg){
		 alert( "Error !: " + msg );
		},
		success:function(data){
			//affiche le contenu du fichier dans le conteneur dédié
			$('#contenu_prix_ajax_mobile').html(data);}
	 	});
 	});
});


{% if commande.statut == "en cours" %}
if (window.location.search.indexOf('action=modif') > -1) {
{% endif %} 
    $.ajax({
	  url: 'ajout-ligne-mobile-options',
	  data: "test=ok&id_forfait={{ligneCommande.abonnement_mobile}}&id_commande={{ligneCommande.id}}&commande={{commande.id}}",
	  success: function(data){
		$('#contenu_options_ajax').html(data);
	  },
	  error: function(){
		alert('failure');
	  }
	});	
{% if commande.statut == "en cours" %}
}
{% endif %} 

var _hidediv = null;
function showdiv(id) {
    if(_hidediv)
        _hidediv();
    var div = document.getElementById(id);
    div.style.display = 'block';
    _hidediv = function () { div.style.display = 'none'; };
}
</script>

<form method="post" class="form-inline" name="form" id="form" >
<fieldset>
		<legend>Création d'une ligne mobile {{commande.statut}}</legend>
       
  
  


		<div class="row-fluid">
  		<div class="controls span3">
        <label  for="id_commande">Numéro de commande:</label>
        {% if commande.statut == "en cours" %}
		<input name="id_commande" type="text" class="uneditable-input" value="{{commande.id}}"/>
        {% else %}
			{{ligneCommande.id_commande}} 
            <input name="id_commande" type="hidden"  value="{{ligneCommande.id_commande}}"/>
		{% endif %} 
	  	</div>
		
		<div class="controls span3">
        <label  for="utilisateur">Utilisateur:</label>
		{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
			<input name="utilisateur" id="utilisateur" type="text" value="{% if ligneCommande.duplicate != 'oui' %}{{ligneCommande.utilisateur}}{% endif %}"  required/> 
		{% else %}
			{{ligneCommande.utilisateur}}
		{% endif %}
		</div>
		
		<div class="controls span3">
        <label  for="carte_sim">Numéro de carte SIM:</label> 
		{% if (commande.statut == "en cours" and sim == "") or ligneCommande.duplicate == 'oui'%}
			  <select name="carte_sim" id="combobox" size="1">
			  	{% for carte_sim in cartes_sim %}
					  <option value="{{carte_sim.transatelId}}">{{carte_sim.transatelId}}</option>
				{% endfor %}
			</select>	
		{% else %}
			{{ligneCommande.carte_sim}}
            <input name="carte_sim" id="carte_sim" type="hidden" value="{{ligneCommande.carte_sim}}" /> 
		{% endif %}	
		</div>
</div>
</fieldset>	  

<fieldset>
			<legend>Engagement</legend>
<div class="row-fluid">
	{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}            
            {% if not(session.niveauAuth=='9') %}
            <!--  <div class="span2">
            <label class="radio">
    		<input type="radio" name="engagement" id="engagement" value="0" {% if ligneCommande.engagement == "0" %}checked{% endif %}> Sans Engagement
  			</label>
            </div>-->
            {% endif %}
            <div class="span2">
            <label class="radio">
    		<input type="radio" name="engagement" id="engagement" value="0" {% if ligneCommande.engagement == "0" %}checked{% endif %}> Sans Engagement
  			</label>
            </div>
            {% if not(session.niveauAuth=='9') %}
            <div class="span2">
            <label class="radio">
    		<input type="radio" name="engagement" id="engagement" value="12" {% if ligneCommande.engagement == "12" %}checked{% endif %}> 12 mois
  			</label>
            </div>
            <div class="span2">
            <label class="radio">
    		<input type="radio" name="engagement" id="engagement" value="24" {% if ligneCommande.engagement == "24" %}checked{% endif %}> 24 mois
  			</label>
            </div>
            <div class="span2">
            <label class="radio">
    		<input type="radio" name="engagement" id="engagement" value="36" {% if ligneCommande.engagement == "36" %}checked{% endif %}> 36 mois
  			</label>
            </div>
            {% endif %}
	{% else %}
    		{% if ligneCommande.engagement == "0" %}
            Sans Engagement
            {% else %}
    		{{ligneCommande.engagement}} mois
            {% endif %}
    {% endif %}	 
     
</div>		  
</fieldset>

<fieldset>
			<legend>Portabilité</legend>
<div class="row-fluid">            
            
            {% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
            <div class="controls span2">
            <label class="checkbox"> 
            <input type="checkbox" name="portabilite" id="portabilite" value="portabilite" onClick="GereControle('portabilite', 'numero_rio', '0');GereControle('portabilite', 'msisdn', '0');GereControle('portabilite', 'date_souhaite', '0')" {% if ligneCommande.msisdn != "" %}checked{% endif %}> Activer la portabilité
            </label>
            </div>
			{% endif %}	
            
			<div class="controls span3">
            <label for="msisdn">Numéro de ligne: </label>
				{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui' %}
				<input name="msisdn" id="msisdn" type="text" value="{% if ligneCommande.duplicate != 'oui' %}{{ligneCommande.msisdn}}{% endif %}" placeholder="33XXXXXXXXX" {% if ligneCommande.msisdn == "" %}disabled{% endif %} onKeypress="return verif_saisie(event);" maxlength="11"  required/> 
				{% else %}
					{{ligneCommande.msisdn}}
				{% endif %}	
			</div>
			
			<div class="controls span3">
            <label for="numero_rio">Numéro de RIO: </label>
			{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
				<input name="numero_rio" type="text" id="numero_rio" value="{% if ligneCommande.duplicate != 'oui' %}{{ligneCommande.numero_rio}}{% endif %}" {% if ligneCommande.msisdn == "" %}disabled{% endif %} onKeypress="return verif_saisie(event);" maxlength="12" required/> 
			{% else %}
				{{ligneCommande.numero_rio}}
			{% endif %}			
			</div>
			
			<div class="controls span3">
            <label for="date_souhaite">Date souhaitée: </label>
			{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
				<input name="date_souhaite" readonly='true' id="date_souhaite" type="text" value="{{ligneCommande.date_souhaite}}" {% if ligneCommande.msisdn == "" %}disabled{% endif %} maxlength="10" required/> 
			{% else %}
				{{ligneCommande.date_souhaite}}
			{% endif %}
			</div>
		  
</div>		  
</fieldset>	
	
<fieldset>
	<legend>Terminal mobile engagement de la sim sur 24 mois</legend>
    
		{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
		<div class="span2">
			<label class="checkbox">
            <input type="checkbox" id="equipement" name="equipement" value="equipement" onClick="GereControle('equipement', 'terminal_mobile', '0');GereControle('equipement', 'numero_imei', '0');" {% if ligneCommande.terminal_mobile != "" %}checked{% endif %}> Choix de l'équipement 
            </label>
	  	</div>
        {% endif %}
		
        <div class="controls span4">
        	<label  for="terminal_mobile">Désignation:</label>
            {% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
			<select name="terminal_mobile" id="terminal_mobile" size="1" {% if ligneCommande.terminal_mobile == "" %}disabled{% endif %}>
            <option value="">Choississez...</option>
            {% for terminal_mobile in terminaux_mobile %}
            <option value="{{terminal_mobile.id}}" {% if ligneCommande.terminal_mobile == terminal_mobile.id %}selected{% endif %}>{{terminal_mobile.libelle}}</option>
			{% endfor %}
			</select> {% if ligneCommande.terminal_prix %}{{ligneCommande.terminal_prix}} € HT{% endif %}
            {% else %}
				{{ligneCommande.nom_terminal}}: {{ligneCommande.terminal_prix}} € HT
			{% endif %}
		</div>
			
		<div class="controls span4">
            <label  for="numero_imei">Numéro IMEI:</label>
            {% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
			<input name="numero_imei" id="numero_imei" type="text" value="{% if ligneCommande.duplicate != 'oui' %}{{ligneCommande.numero_imei}}{% endif %}" {% if ligneCommande.terminal_mobile == "" %}disabled{% endif %} onKeypress="return verif_saisie(event);"/>
            {% else %}
				{{ligneCommande.numero_imei}} 
            {% endif %}
		</div>

	   </fieldset>
	  
	   <fieldset>
			<legend>Abonnement</legend>

		 <div class="control-group">
			<label class="control-label" for="abonnement_mobile">Offre principale {{ commande.statut}}</label>
			<div class="controls">
			{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
				<select name="offre" id="offre" >
                <option value="">Choississez...</option>
				{% for offre_mobile in offres_mobile %}
				<option value="{{offre_mobile.id}}" {% if ligneCommande.offre == offre_mobile.id %}selected{% endif %}>{{offre_mobile.nom}}</option>
				{% endfor %}
				</select> 
                <div id="contenu_prix_ajax_mobile">
		</div>
                {% if ligneCommande.prix %}{{ligneCommande.prix}} € HT{% endif %}
			{% else %}
				{{ligneCommande.offre}}: {{ligneCommande.prix}} € HT
			{% endif %}
			</div>
		  </div>			
		
        
        <div id="contenu_options_ajax">
		</div>
        <div id="interne" class="interne" style="display: none;">
        Appel interne: <textarea cols="10" rows="3" name="appel_interne" placeholder="numéros séparés par des virgules: 336xxxxxxxx,336xxxxxxxx">{{ligneCommande.interne}}</textarea>
        </div>
        </fieldset>
        <fieldset>
        {% if not(session.niveauAuth=='9') %}
	<legend>Condition particulières tarifaires</legend>

	
	  <div class="control-group">
      
		<label class="control-label" for="identifiant_adv">Identifiant ADV</label>
		<div class="controls">
		   <input name="identifiant_adv" type="text" value="{{ligneCommande.identifiant_adv}}" placeholder="numero d'adhérent"/> 
		</div>
	  </div>
	   
<fieldset>
<strong>Réduction </strong></fieldset>
<div class="span5">
	  <div class="control-group">
     
		<label class="control-label" for="abonnement">Abonnement</label>
		<div class="controls">
		   <input name="abonnement" type="text" value="{{ligneCommande.abonnement}}" placeholder="%"/> 
		</div>
	  </div>
        <div class="control-group">
		<label class="control-label" for="minute_national">Min National </label>
		<div class="controls">
		   <input name="minute_national" type="text" value="{{ligneCommande.minute_national}}" placeholder="%"/> 
		</div>
	  </div>
        <div class="control-group">
		<label class="control-label" for="minute_international">Min International </label>
		<div class="controls">
		   <input name="minute_international" type="text" value="{{ligneCommande.minute_international}}" placeholder="%"/> 
		</div>
	  </div>	
	  </div>
	  <div class="span6">

	   <div class="control-group">
		<label class="control-label" for="option_mobile">Option Mobile </label>
		<div class="controls">
		   <input name="option_mobile" type="text" value="{{ligneCommande.option_mobile}}" placeholder="%"/> 
		</div>
	  </div>
	   <div class="control-group">
		<label class="control-label" for="mobil">Mobile </label>
		<div class="controls">
		   <input name="mobil" type="text" value="{{ligneCommande.mobil}}" placeholder="%"/> 
		</div>
	  </div>
	 
	   <div class="control-group">
		<label class="control-label" for="grille_tarifaire">Grille tarifaire de vente</label>
		<div class="controls">
		   <select name="grille_tarifaire" size="1">
		   <option value="">Selectionnez...</option>
			  <option value="tarif_1"{% if ligneCommande.grille_tarifaire == "tarif_1" %}selected{% endif %}>Tarif 1</option>
			  <option value="tarif_2"{% if ligneCommande.grille_tarifaire == "tarif_2" %}selected{% endif %}>Tarif 2</option>
			  <option value="tarif_3"{% if ligneCommande.grille_tarifaire == "tarif_3" %}selected{% endif %}>Tarif 3</option>
			  <option value="tarif_4"{% if ligneCommande.grille_tarifaire == "tarif_4" %}selected{% endif %}>Tarif 4</option>
              <option value="tarif_5"{% if ligneCommande.grille_tarifaire == "tarif_5" %}selected{% endif %}>Tarif 5</option> 
               <option></option>
			</select>
		</div>
	  </div>
	    </div>
	  {% endif %}
	</fieldset>
        
	
	{% if commande.statut == "en cours" or ligneCommande.duplicate == 'oui'%}
	<div class="row">
		<div class="span12">
		<div class="form-actions">
		<span>Action après validation</span>
		<br/>
		  <select name="next">
			<option value="creation-commande">Retour à la commande</option>
			<option value="ajout-ligne-mobile">Ajouter une nouvelle ligne</option>
            {% if ligneCommande.id is empty or ligneCommande.duplicate == 'oui' %}
			<option value="dupliquer-ligne">Dupliquer cette ligne</option>
            {% endif %}
			<option value="liste-client">Afficher la liste des clients</option>
		  </select>
		<br/><br/>
		{% if ligneCommande.id is empty or ligneCommande.duplicate == 'oui' %}
			<button type="submit" class="btn btn-primary" name="action" value="create">Ajouter</button>
		{% else %}
			<button type="submit" class="btn btn-primary" name="action" value="update">Mettre à jour</button>
		{% endif %}
		</div>
		</div>
	</div>
	{% endif %}
	
	   
	
</form>
{% endblock %}